<!--
    选择自定义人员
    params:
        visible: 是否打开人员窗口
        checked: 选中人员
        multiple: 是否多选
    emit:
        update:visible
        update:checked
        cancel
 -->
<template>
	<el-dialog
		class="select-deps-staff-component"
		title="选择人员"
		v-model="onChoiceStaff"
		:show-close="false"
		width="800px"
		:close-on-click-modal="false"
		:append-to-body="appendToBody"
		@close="cancelBind"
	>
		<div class="content">
			<div class="over">
				<div class="heiscoll" style="flex: 35%">
					<div>选择部门</div>
					<div class="mt10 eltree" style="margin-right: 10px">
						<el-tree
							ref="depRef"
							:data="departmentAllTree"
							:props="{
								label: 'title',
								value: 'value'
							}"
							node-key="id"
							clearable
							:current-node-key="null"
							default-expand-all
							:expand-on-click-node="false"
							highlight-current
							:value="staffFilterForm.departmentId"
							@node-click="onSelectDepartment"
						>
							<template #default="{ node }">
								<span class="custom-tree-node">
									<span>
										<!-- <ww-open-data style="font-size: 14px;" type='departmentName' :openid='node.data.id'/> -->
										{{ node.label }}
									</span>
								</span>
							</template>
						</el-tree>
					</div>
				</div>
				<div class="heiscoll" :style="multiple ? { flex: '32.5%' } : { flex: '75%' }">
					<div>员工姓名</div>
					<div style="margin-bottom: 10px">
						<!-- <el-input
							v-model="staffFilterForm.search"
							placeholder="请输入"
							size="small" clearable
							@keypress.enter.native="getStaffList()"
						>
							<el-button
								slot="append"
								size="small"
								icon="el-icon-search"
								@click="getStaffList()"
							/>
						</el-input> -->
					</div>
					<div>
						<template v-if="staffList.length > 0">
							<!-- 多选check -->
							<template v-if="multiple">
								<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"
									>全选</el-checkbox
								>
								<div v-for="item in staffList" :key="item.userId" style="height: 20px">
									<el-checkbox :value="item.userId" v-model="selectedStaffIds" @change="onCheckboxCheck(item)">
										{{ item.name }}
									</el-checkbox>
								</div>
							</template>

							<!-- 单选radio -->
							<template v-else>
								<div
									v-for="item in staffList"
									:key="item.userId"
									style="height: 20px"
									@click="searchDepartmentId(item.departmentId)"
								>
									<el-radio :value="item.userId" v-model="selectedStaffIds[0]" @input="onRadioCheck(item)">
										{{ item.name }}
									</el-radio>
								</div>
							</template>
						</template>
						<span v-else>暂无数据</span>
					</div>
					<div>
						<!-- <el-pagination
							class="tableblock__pagination"
							layout="prev, pager, next"
							:total="staffTotal"
							:page-size.sync="staffPrePage"
							:current-page="staffCurrentPage"
							@current-change="getStaffList"
						/> -->
					</div>
				</div>

				<!-- 多选时显示选中人员面板 -->
				<div v-if="multiple" class="heiscoll" style="flex: 32.5%">
					<div>选中人员<el-button type="text" class="clearBnt fr" @click="clearAll">全部移除</el-button></div>
					<div class="selectedContainer mt10">
						<el-tag v-for="item in selectedStaff" :key="item.employeeId" closable @close="removeStaff(item)">
							{{ item.employeeName }}
						</el-tag>
					</div>
				</div>
			</div>
		</div>
		<template #footer>
			<span>
				<el-button type="primary" @click="onConfirmSelect"> 确 定 </el-button>
				<el-button @click="cancelBind">取 消</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script>
	import tool from '@/utils/tool'
	import customerQwOrderApi from '@/api/biz/customerQwOrderApi'
	export default {
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			checked: {
				type: Array,
				default: () => []
			},
			multiple: {
				type: Boolean,
				default: false
			},
			required: {
				// 必选检查
				type: Boolean,
				default: true
			},
			departmentList: {
				type: Array,
				default: () => []
			},
			appendToBody: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				selectedStaff: [], // 选中人员
				selectedStaffIds: [], // 选中人员id集合，便于匹配
				isIndeterminate: false, // 全选样式控制
				checkAll: false, // 是否全选

				// 选择员工
				onChoiceStaff: false,
				departmentAllTree: [],
				staffList: [],
				staffCurrentPage: 0,
				staffPrePage: 50,
				staffTotal: 0,

				// 筛选条件
				staffFilterForm: {
					search: '',
					departmentId: null
				}
			}
		},
		computed: {},
		watch: {
			visible(n, o) {
				this.onChoiceStaff = n
				if (n) {
					//     // 人员及部门接口预加载
					//     this.getDepartmentTree();
					//     this.getStaffList();

					// 外部带动打开窗口处理
					this.selectedStaff = tool.deepClone(this.checked)
					this.selectedStaffIds = this.selectedStaff.map((item) => item.userId)
					this.setCheckAllStatus()

					// 不做反显
					// this.selectedStaff = [];
					// this.selectedStaffIds = [];
				}
			},
			onChoiceStaff(n, o) {
				this.$emit('update:visible', n)
			}
		},
		created() {
			// debugger
			// // 设置默认选中部门【根部门默认1】
			// this.staffFilterForm.departmentId = '1';
			// 人员及部门接口预加载
			this.getDepartmentTree()
			this.getStaffList()
		},
		methods: {
			// 人员单选
			onRadioCheck(row) {
				this.selectedStaffIds = [row.userId]
				this.selectedStaff = [row]
			},
			// 人员多选
			onCheckboxCheck(row) {
				// 选中-检查是否已存在，不存在则push，存在则移除
				const index = this.selectedStaffIds.indexOf(row.userId)
				if (index > -1) {
					this.selectedStaffIds.splice(index, 1)
					this.selectedStaff.splice(index, 1)
				} else {
					this.selectedStaffIds.push(row.userId)
					this.selectedStaff.push(row)
				}

				this.setCheckAllStatus()
			},
			// 多选全选
			handleCheckAllChange(val) {
				this.isIndeterminate = false
				if (val) {
					// 去除已被选中的内容
					let selected = []
					selected = this.staffList.reduce((total, item) => {
						if (!this.selectedStaffIds.includes(item.userId)) {
							total.push(item)
						}
						return total
					}, [])

					this.selectedStaff = this.selectedStaff.concat(selected)
					this.selectedStaffIds = this.selectedStaff.map((item) => item.userId)
				} else {
					// 取消当前页面的选中
					let selected = []
					selected = this.selectedStaff.reduce((total, item) => {
						// 当前人员在这个页面里面， 那么从中移除，不在的话则跳过
						if (!this.staffList.some((child) => item.userId === child.userId)) {
							total.push(item)
						}
						return total
					}, [])

					this.selectedStaff = selected
					this.selectedStaffIds = this.selectedStaff.map((item) => item.userId)
				}
			},
			// 全部移除
			clearAll() {
				this.selectedStaffIds = []
				this.selectedStaff = []
				this.checkAll = false
			},
			// 单个移除
			removeStaff(item) {
				this.onCheckboxCheck(item)
			},
			// 设置全选状态
			setCheckAllStatus() {
				if (this.multiple) {
					this.checkAll =
						this.staffList.length < this.selectedStaffIds.length &&
						this.staffList.every((child) => this.selectedStaffIds.includes(child.userId))
					this.isIndeterminate =
						!this.checkAll && this.staffList.some((child) => this.selectedStaffIds.includes(child.userId))
				}
			},

			/**
			 * 部门树选中
			 * @param {Number} id 数据ID
			 */
			onSelectDepartment(data, node, nodes) {
				this.staffFilterForm.departmentId = data.value
				this.getStaffList()
			},
			/**
			 * 人员选择定位部门
			 * @param {Number} id 数据ID
			 */
			searchDepartmentId(ID) {
				// console.log('ID', ID)
				this.staffFilterForm.departmentId = ID
			},
			/**
			 * 获取员工数据数据（根据筛选）
			 * @param {Number} page 页码
			 */
			getStaffList() {
				const params = {
					//     pageNum: page,
					//     pageSize: this.staffPrePage,
					//     // isDimission: false,
					//     // isAdmin: false,
				}

				if (this.staffFilterForm.departmentId) {
					params.departmentId = this.staffFilterForm.departmentId
				}

				if (this.staffFilterForm.search !== '') {
					params.employeeName = this.staffFilterForm.search
				}

				customerQwOrderApi.getEmpByDeptId(params).then((res) => {
					// const { dataPermission, departmentId } = this.$store.state.userInfo
					// this.staffList = dataPermission > 2 ? res : res.filter(item => item.departmentId === departmentId.toString());
					this.staffList = res

					// 更新全选状态
					this.setCheckAllStatus()
					// this.staffCurrentPage = res.pageNum
					// this.staffPrePage = res.pageSize
					// this.staffTotal = res.total
				})
			},
			/**
			 * 获取并处理组织结构
			 */
			getDepartmentTree() {
				if (this.departmentList.length) {
					// 设置默认选中部门【根部门默认1】
					this.staffFilterForm.departmentId = this.departmentList[0].id
					this.departmentAllTree = this.departmentList
					return
				}
				// 设置默认选中部门【根部门默认1】
				this.staffFilterForm.departmentId = 1
				customerQwOrderApi.getDeptTree().then((res) => {
					this.departmentAllTree = tool.analyticDepartmentTree([res])
				})
			},
			/**
			 * 确认选中员工
			 */
			onConfirmSelect() {
				if (this.required && (!this.selectedStaff || this.selectedStaff.length === 0)) {
					this.$message.warning('请先选择一名员工')
					return false
				}

				this.$emit('update:checked', this.selectedStaff)
				this.onChoiceStaff = false
			},
			/**
			 * 关闭自定义选择面板
			 */
			cancelBind() {
				// 进行数据恢复
				this.onChoiceStaff = false
				this.$emit('cancel')
			}
		}
	}
</script>

<style lang="less" scoped>
	.select-deps-staff-component {
		.content .over {
			display: flex;
			gap: 10px;
		}

		.selectedContainer {
			display: flex;
			flex-wrap: wrap;
			gap: 4px;
		}
		.clearBnt {
			line-height: 0;
		}
	}

	.heiscoll {
		max-height: 350px;
		overflow: auto;
	}
	.mt10 {
		margin-top: 10px;
	}
</style>
